#!/usr/bin/env python
"""
诊断音色加载问题
"""
import sys
import torch
from pathlib import Path

project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.utils.config_manager import get_config
from src.services.chattts_engine import ChatTTSEngine

print("=" * 70)
print(" " * 20 + "音色加载诊断")
print("=" * 70)
print()

# 获取配置
config = get_config()
tts_config = config.get_tts_config()

print("配置文件设置:")
print(f"  device: {tts_config.get('device')}")
print(f"  speaker_seed: {tts_config.get('speaker_seed')}")
print(f"  speaker_file: {tts_config.get('speaker_file')}")
print()

# 检查音色文件
speaker_file = project_root / tts_config.get('speaker_file', '')
if speaker_file.exists():
    print(f"✓ 音色文件存在: {speaker_file}")
    
    # 加载并检查音色
    spk_saved = torch.load(speaker_file, weights_only=True)
    print(f"  音色形状: {spk_saved.shape}")
    print(f"  音色设备: {spk_saved.device}")
    print(f"  音色类型: {spk_saved.dtype}")
    print()
else:
    print(f"✗ 音色文件不存在: {speaker_file}")
    print()

# 初始化引擎（使用配置）
print("=" * 70)
print("初始化TTS引擎...")
print("=" * 70)
print()

engine = ChatTTSEngine(
    device=tts_config.get('device', 'cuda'),
    compile=False,
    source=tts_config.get('source', 'huggingface'),
    temperature=tts_config.get('temperature', 0.3),
    top_p=tts_config.get('top_p', 0.7),
    top_k=tts_config.get('top_k', 20),
    enable_refine=False,
    speaker_seed=tts_config.get('speaker_seed'),
    speaker_file=tts_config.get('speaker_file')
)

print()
print("=" * 70)
print("检查引擎状态")
print("=" * 70)
print()

if engine.spk_emb is not None:
    print(f"✓ 引擎音色已加载")
    print(f"  音色形状: {engine.spk_emb.shape}")
    print(f"  音色设备: {engine.spk_emb.device}")
    print(f"  音色类型: {engine.spk_emb.dtype}")
    
    # 对比音色
    if speaker_file.exists():
        spk_saved = torch.load(speaker_file, weights_only=True, map_location=engine.device)
        difference = torch.abs(engine.spk_emb - spk_saved).mean().item()
        print(f"  与文件差异: {difference:.8f}")
        
        if difference < 0.0001:
            print("  ✓ 音色完全一致！")
        else:
            print("  ✗ 音色不一致！可能音色未正确加载")
else:
    print("✗ 引擎音色未加载")

print()
print("=" * 70)
print("诊断完成")
print("=" * 70)
